﻿
using System.Collections.Generic;
using UnityEngine;
using WooEngine.Common;
using WooEngine.Security;
using WooEngine.Utility.Base;
using WooEngine.Utility.Logger;
using WooEngine.Utility.Security.Base;

namespace WooEngine.ConfigWork
{
    public enum ConfigFileType
    {
        DATA = 0, //单独的数据
        TEMPLATE = 1, //合并到一起的数据
        LANG = 2,// 语言文本。
    }

    public class ConfigManager : SingletonBehaviour<ConfigManager>
    {
        private string m_secretKey = "";
        private Dictionary<string, ConfigFileData> m_dic = new Dictionary<string, ConfigFileData>();


        public void SetSecretKey(string secretKey)
        {
            m_secretKey = secretKey;
        }

        public void AddFile(TextAsset res, string fileName = null, bool isEn = false)
        {
            if (!res)
            {
                WooLogger.ErrorAppendString(" init file res is null", fileName);
                return;
            }

            string data = res.text;
            if (isEn)
            {
                data = EncryptionUtils.TextDecrypt(res.text, m_secretKey);
            }

            ConfigFileAsset asset = JsonUtility.FromJson<ConfigFileAsset>(data);
            if (asset.IsEncode)
            {
                asset.data = this.decode(asset.data);
            }
            else
            {
                asset.data = data.Substring( 21, data.Length - 22);
            }

            asset.Init();
            
            if (asset.json.HasField("type") && asset.json.GetField("type").n == (int)ConfigFileType.TEMPLATE)
            {
                JSONObject room = asset.json.GetField("data");
                foreach (string key in room.keys)
                {
                    this.m_dic.Add(key, new ConfigFileData(room.GetField(key)));
                }
            }
            else
            {
                if (fileName != null)
                {
                    if (!this.m_dic.ContainsKey(fileName))
                    {
                        this.m_dic.Add(fileName, new ConfigFileData(asset.json));
                    }
                }
                else
                {
                    WooLogger.Error("不是合成表，fileName 不能为空");
                }
            }
        }


        private string  decode(string s)
        {
            return Base64zh.decode(s);
        }

        public ConfigFileData GetConfigFileData(string fileName) {
            if (m_dic.ContainsKey(fileName))
            {
                return this.m_dic[fileName];
            }
            WooLogger.ErrorAppendString(" config error get fileName:", fileName);
            return null;
        }

        public void clear()
        {
            this.m_dic.Clear();
        }
    }
}
